<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>WebSocket Demo</title>
</head>
<body>
  <h2>WebSocket 简单示例</h2>
  <button onclick="connect()">连接</button>
  <button onclick="sendMsg()">发送消息</button>
  <div id="output"></div>

  <script>
    let socket;

    function connect() {
      socket = new WebSocket("ws://localhost:8000"); // 连接到后端 8000 端口
      socket.onopen = () => {
        document.getElementById("output").innerHTML += "<p>已连接</p>";
      };
      socket.onmessage = (event) => {
        document.getElementById("output").innerHTML += "<p>收到: " + event.data + "</p>";
      };
      socket.onclose = () => {
        document.getElementById("output").innerHTML += "<p>连接关闭</p>";
      };
    }

    function sendMsg() {
      if (socket && socket.readyState === WebSocket.OPEN) {
        socket.send("你好，服务器！");
      }
    }
  </script>
</body>
</html>
